/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mysgoog.bot;

import mysgoog.board.*;
import mysgoog.bot.algo.*;
import mysgoog.gtp.*;
import mysgoog.util.*;

/**
 * 
 * @author ysy
 */
public class SearchBot extends GoBot
{
    Board board;
    private int[] search_moves;
    private int search_res;

    @Override
    public void setBoard(Board board)
    {
        this.board = board;
        search_moves = new int[board.BOARD_ELEMNUM];
    }
    @Override
    public Vertex genMove(Color color)
    {
        Color other = color.complement();
        boolean find = false;
        for (Worm w : board.getWorms(other))
        {
            for (Integer pos : w)
            {
                search_res = AlphaBetaSearch.Capture(board, pos, search_moves); // ab.Defend(board,
                if (search_res > 0)
                {
                    find = true;
                    break;
                } else
                    search_res = 0;
            }
            if (find)
                break;
        }
        if (search_res <= 0)
        {
            for (Worm w : board.getWorms(color))
            {
            	if(w.getLibs().size()==1){
	                for (Integer pos : w)
	                {
	                    search_res = AlphaBetaSearch.Defend(board, pos, search_moves); // ab.Defend(board,
	                    if (search_res != 0)
	                    {
	                        find = true;
	                        break;
	                    } else
	                        search_res = 0;
	                }
	                if (find)
	                    break;
            	}
            }
        }
        if (search_res == 0 || search_res == -1)
        {
            Lib.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~B");
            if (board.getTurn() >= board.BOARD_ELEMNUM)
                return new Vertex("pass");
            while (true)
            {
                int x = Lib.random(board.BOARD_LENGTH);
                int y = Lib.random(board.BOARD_LENGTH);
                if (board.isLegal(color, board.makePos(x, y)))
                {
                    return new Vertex(x, y);
                }
            }
        } else
        {
            Lib.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~C");
            int pos = search_moves[0];
            if(board.isLegal(color, pos))
            	return new Vertex(board.posX(pos), board.posY(pos));
            else
            	return new Vertex(-1,-1);
        }
    }
}
